package pattern5.ProducerConsumer.demo1.msgServer;

import com.alibaba.fastjson.JSON;
import utils.PrintUtil;

import java.util.LinkedList;
import java.util.Queue;

/**
 * @创建人 liweijia
 * @创建时间 2022/7/30
 * @描述 程序的主要用途
 */
public class MsgManager {

    /**
     * 消息队列
     */
    private final Queue<Msg> msgQueue;

    /**
     * 最大长度
     */
    private final Integer maxSize;

    public MsgManager(Integer queueSize) {
        this.msgQueue = new LinkedList<>();
        this.maxSize = queueSize;
    }


    /**
     * 发送消息
     *
     * @param msg
     */
    public void send(Msg msg) {
        synchronized (msgQueue) {
            if (msgQueue.size() > maxSize) {
                PrintUtil.print("消息队列满了，执行拒绝策略，直接拒绝");
                return;
            }
            PrintUtil.print(String.format("生产者生产消息[%s],msgQueue=%d", JSON.toJSONString(msg), msgQueue.size()));
            msgQueue.offer(msg);
            msgQueue.notifyAll();
        }
    }

    /**
     * 取消息
     */
    public Msg take() {
        synchronized (msgQueue) {
            while (msgQueue.isEmpty()) {
                if (Thread.currentThread().isInterrupted()) {
                    PrintUtil.print("消费者被打断");
                }
                try {
                    msgQueue.wait();
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
            Msg msg = msgQueue.poll();
            msgQueue.notifyAll();
            return msg;
        }
    }
}
